package com.xpu.stock.service.impl;

import com.google.common.base.Strings;
import com.xpu.stock.mapper.SysUserMapper;
import com.xpu.stock.pojo.SysUser;
import com.xpu.stock.service.UserService;
import com.xpu.stock.utils.IdWorker;
import com.xpu.stock.vo.req.LoginReqVo;
import com.xpu.stock.vo.resp.LoginRespVo;
import com.xpu.stock.vo.resp.ResponseCode;
import com.xpu.stock.vo.resp.Result;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 定义用户实现
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Override
    public Result<LoginRespVo> login(LoginReqVo vo) {
        if(vo==null|| Strings.isNullOrEmpty(vo.getUsername())||Strings.isNullOrEmpty(vo.getPassword())
        ||Strings.isNullOrEmpty(vo.getCode())||Strings.isNullOrEmpty(vo.getRkey())){
            return Result.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //先校验验证码，因为校验码从内存获取，不走IO效率更高
        //获取redis中rkey对应的验证码
        String redisCode = (String)redisTemplate.opsForValue().get(vo.getRkey());
        if (redisCode==null||!redisCode.equals(vo.getCode())) {
            return Result.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //快速淘汰校验码，合理利用redis内存空间
        redisTemplate.delete(vo.getRkey());
        //根据用户名查询用户信息
        SysUser user=this.sysUserMapper.findByUserName(vo.getUsername());
        //判断用户是否存在，存在则密码校验比对
        if (user==null || !passwordEncoder.matches(vo.getPassword(),user.getPassword())){
            return Result.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //组装登录成功数据
        LoginRespVo respVo = new LoginRespVo();
        //属性名称与类型必须相同，否则copy不到
        BeanUtils.copyProperties(user,respVo);//spring给我们提供的工具类，属性复制
        return  Result.ok(respVo);

    }

    @Override
    public Result<Map> genCaptchaCode() {
        //1.生成随机校验码，长度为4
        String checkCode = RandomStringUtils.randomNumeric(4);
        //2.生成一个类似sessionid的ID作为key，然后校验码作为value保存redis下，同时设置有效时间为60秒
        String sessionId = String.valueOf(idWorker.nextId());
        redisTemplate.opsForValue().set(sessionId,checkCode,2, TimeUnit.MINUTES);
        //3.组装响应的map对象
        HashMap<String, String> map = new HashMap<>();
        map.put("code",checkCode);
        map.put("rkey",sessionId);
        //返回组装数据
        return Result.ok(map);
    }
}
